package com.shxs.service.impl;
import java.io.File;
import java.util.*;

import com.shxs.model.entity.User;
import com.shxs.model.entity.Dialog;
import com.shxs.model.entity.MINIMAX.TimberWeights;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxs.mapper.MINIMAXRequestMapper;
import com.shxs.model.entity.MINIMAX.MINIMAXRequest;
import com.shxs.model.entity.VoiceGenerateRequest;
import com.shxs.service.MINIMAXService;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

/**
 * 语音生成服务实现
 *
 */
@Service
public class MINIMAXServiceImpl extends ServiceImpl<MINIMAXRequestMapper, MINIMAXRequest>
    implements MINIMAXService {

    /**
     * 青涩男声：male-qn-qingse
     * 精英男生：male-qn-jingying
     * 霸道青年音色：male-qn-badao
     * 青年大学生音色：male-qn-daxuesheng
     * 男性主持人：presenter_male
     * 男性有声书1：audiobook_male_1
     * 男性有声书2：audiobook_male_2
     * 少女音色：female-shaonv
     * 御姐音色：female-yujie
     * 成熟女性音色：female-chengshu
     * 甜美女性音色：female-tianmei
     * 女性主持人：presenter_female
     * 女性有声书1：audiobook_female_1
     * 女性有声书2：audiobook_female_2
     */

    @Value("${shxs.path}")
    private String basePath;

    private static Map<String, String> vg_vi;
    private static List<String> keys=new ArrayList<String>();
    private static long begin;
    private static int count=0;
    private static int num=0;
    static {
        HashMap<String, String> hs_map = new HashMap<>();
        hs_map.put("青涩男声", "male-qn-qingse");
        hs_map.put("精英男生", "male-qn-jingying");
        hs_map.put("霸道青年音色", "male-qn-badao");
        hs_map.put("青年大学生音色", "male-qn-daxuesheng");
        hs_map.put("男性主持人", "presenter_male");
        hs_map.put("男性有声书1", "audiobook_male_1");
        hs_map.put("男性有声书2", "audiobook_male_2");
        hs_map.put("少女音色", "female-shaonv");
        hs_map.put("御姐音色", "female-yujie");
        hs_map.put("成熟女性音色", "female-chengshu");
        hs_map.put("甜美女性音色", "female-tianmei");
        hs_map.put("女性主持人", "presenter_female");
        hs_map.put("女性有声书1", "audiobook_female_1");
        hs_map.put("女性有声书2", "audiobook_female_2");
        vg_vi = hs_map;
        begin=System.currentTimeMillis();
        keys.add("1793266516951580720");
        keys.add("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmnY7mlofmnbAiLCJVc2VyTmFtZSI6IuadjuaWh-adsCIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxNzkzMjY2NTE2OTU5OTY5MzI4IiwiUGhvbmUiOiIxNzUwNTg0NzY4OCIsIkdyb3VwSUQiOiIxNzkzMjY2NTE2OTUxNTgwNzIwIiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjQtMDUtMjQgMTU6MzU6NDQiLCJpc3MiOiJtaW5pbWF4In0.vbZ8Ge56_22dwscrg3qCDgo0YylhpVA9rihxc-GJOFFjujYaixcne39Pb3-Chs4dBVbsT4U87smrn5S8jX7bM3awl0jwl5BpgYJtt1lB8K7C7UMCjZ72ByCteSi1eltuckRygcgd1C84x9S9vHfaY7RXQSGqthX5SdLkhp5dYmyAiVdWligXUqsWJ9-xngm8OPaa_ZwIDjIUYmUCdm23YhIyVGubwJkkKHAaoGKf84PM6nw2OUr8U_IErie5fq4VbAactXTU4v_d6bPFQeYxPP3C2gxTsETTXy2oyqh7B3WdUyibncMS_UIhSnlFlVv7TUstnwZefD4_66TlvGLgqQ");
        keys.add("1783023729048043885");
        keys.add("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLpqazkuJbmupAiLCJVc2VyTmFtZSI6IumprOS4lua6kCIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOi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EIkMuv5yu_6NHqlPnPSch5iHKLp7Caf2kmQyiWZaz1Ox8FNs670md0tdxjtcgOO7ORptZWgAmAd_bBd8PmOqWP7-QvaQtoDsCdPIHo91MrsTT603VjRgwp8-76D7lexUh1TossXC1Q5NMMDWE9dxmiZQpTlYvdAEwmWeL0y0-4MncMxhE95rLA");
    }

    @Override
    public MINIMAXRequest getMINIMAXRequest(Dialog dialog, VoiceGenerateRequest voiceGenerateRequest) {

        String text = dialog.getText();
        String voice_generator = dialog.getVoice_generator();

        System.out.println(vg_vi);

        String voiceId = vg_vi.get(voice_generator);

        String authorization = voiceGenerateRequest.getAuthorization();
        String groupId = voiceGenerateRequest.getGroupId();

        MINIMAXRequest res = new MINIMAXRequest();
        res.setAuthorization(authorization);
        res.setGroupId(groupId);
        res.setVoiceId(voiceId);
        res.setText(text);

        return res;
    }

    @Override
    public InputStream doRequest(MINIMAXRequest minimaxRequest, Integer index) {

        if(num==3){
            count+=2;
            num=0;
            if(count== keys.size()){
                long elapsedTime = System.currentTimeMillis() - begin;

                if (elapsedTime >= 60000) { // 1 minute = 60,000 milliseconds
                    count=0;
                } else {
                    try {
                        Thread.sleep(elapsedTime); // Sleep for 1 second
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                begin=System.currentTimeMillis();
                count=0;
            }
        }
        num++;
        String authorization = keys.get(count+1);
        String groupId = keys.get(count);
        String voiceId = minimaxRequest.getVoiceId();
        Double speed = minimaxRequest.getSpeed();
        String text = minimaxRequest.getText();

        String apiKey = authorization;
        String url = "https://api.minimax.chat/v1/text_to_speech?GroupId=" + groupId;

        JSONObject data = new JSONObject();
        data.put("voice_id", voiceId);
        data.put("text", text);
        data.put("model", "speech-01");
        data.put("speed", speed);
        data.put("vol", 1.0);
        data.put("pitch", 0);
        data.put("output_format", "mp3");
        JSONObject timber_weights = new JSONObject();
        timber_weights.put("voice_id", voiceId);
        timber_weights.put("weight", 100);
        data.put("timber_weights", new JSONArray().put(timber_weights));
        data.put("char_to_pitch", new JSONArray().put("你/(ni1)"));

        //查看basePath的文件目录是否存在，不存在则创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdir();
        }

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer " + apiKey);
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = data.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                return con.getInputStream();
                /*
                try (InputStream inputStream = con.getInputStream()) {
                    // 将输入流写入到文件中
                    FileOutputStream fileOutputStream = new FileOutputStream(basePath + index + ".mp3");
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }
                    fileOutputStream.close();
                    System.out.println("音频已保存为：" + index + ".mp3");
                }
                 */
            } else {
                System.out.println("请求失败，响应码：" + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
